﻿using Rxbit.Core.Driver;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using uniview;

namespace TSMR01Xml
{
    public delegate void GetServerIpHandler(string str);

    public partial class Form1 : Form
    {
        //public event GetServerIpHandler getServerIpHandler;
        /// <summary>
        /// 定义连接客户端ip
        /// </summary>
        public static string clientIp = "";
        /// <summary>
        /// 定义连接客户端口
        /// </summary>
        public static string clientPort = "";
        public Form1()
        {
            InitializeComponent();
            ///获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            this.ipTextBox.Text = AddressIP;
            this.btnStopListen.Enabled = false;

        }


        private void IpGetButton_Click(object sender, EventArgs e)
        {
            ///获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            this.ipTextBox.Text = AddressIP;
        }

        public static XmlTcpServerEntity xmlTcpServerEntity;
        private void ListenButton_Click(object sender, EventArgs e)
        {            

            this.ListenButton.Enabled = false;
            this.btnStopListen.Enabled = true;
            xmlTcpServerEntity = new XmlTcpServerEntity();
            xmlTcpServerEntity.DataReceived += XmlTcpServerEntity_DataReceived;
            xmlTcpServerEntity.TrafficEventReceived += XmlTcpServerEntity_DataReceivedEvent;
            xmlTcpServerEntity.ClientConnected += XmlTcpServerEntity_ClientConnected;
            xmlTcpServerEntity.Signal101Come += XmlTcpServerEntity_Signal101Come;
            bool result = xmlTcpServerEntity.StartListen(ipTextBox.Text.Trim(), Convert.ToInt32(tbxPort.Text.Trim()));
            if (result)
            {
                this.ConsoleTextBox.AppendText("开始侦听." + Environment.NewLine);
            }
            else
            {
                this.ConsoleTextBox.AppendText("侦听失败." + Environment.NewLine);

            }
        }


        private void XmlTcpServerEntity_Signal101Come()
        {
            Task.Run(() =>
            {
                this.Invoke(new Action(() =>
                {
                    this.label8.BackColor = Color.Lime;
                }));
                Thread.Sleep(1000);
                this.Invoke(new Action(() =>
                {
                    this.label8.BackColor = Color.Red;
                }));
            });
        }

        private void XmlTcpServerEntity_ClientConnected(TcpClient obj)
        {
            this.Invoke(new Action((() => { 
                this.ConsoleTextBox.AppendText($"远程{obj.Client.RemoteEndPoint.ToString()},连接到客户端{ Environment.NewLine}");
                clientIp = obj.Client.RemoteEndPoint.ToString().Split(':')[0];
                clientPort= obj.Client.RemoteEndPoint.ToString().Split(':')[1];
            }
            )));
        }
       
        int count = 0;
        private void XmlTcpServerEntity_DataReceivedEvent(TrafficEvent obj)
        {

            this.Invoke(new Action(() =>
            {

                Control[] ctrls = panel4.Controls.Find(obj.LaneID, true);
                if (ctrls.Length == 0)
                {
                    LaneInfoUserControl userControl = new LaneInfoUserControl(obj.LaneID, obj.TollgateID, obj.PassTime, obj.LaneStatus);
                    userControl.Name = obj.LaneID;
                    userControl.Visible = true;

                    Point point = new Point(10, 10);

                    if (obj.LaneID.Contains("00"))
                    {
                        point = new Point(400, 200);

                    }
                    else
                    {

                        point = new Point(10 + (220 * count++), 10);

                    }

                    userControl.Location = point;
                    userControl.setValue(obj.TollgateID, obj.PassTime, obj.LaneStatus,obj.RecordID,obj.CamID);

                    panel4.Controls.Add(userControl);
                }
                else
                {
                    LaneInfoUserControl tempDgv = ctrls[0] as LaneInfoUserControl;
                    tempDgv.setValue(obj.TollgateID, obj.PassTime, obj.LaneStatus, obj.RecordID, obj.CamID);
                }

            }));
        }

        private void XmlTcpServerEntity_DataReceived(TrafficFlow obj)
        {
            this.Invoke(new Action(() =>
            {
                this.CamID.Text = obj.CamID;
                this.SampleTime.Text = obj.SampleTime.ToString();
                this.Period.Text = obj.Period.ToString();
                this.TollgateIDLabel.Text = obj.TollgateID.ToString();
                this.LaneNum.Text = obj.LaneNum.ToString();
                this.dataGridViewFLow.DataSource = obj.Lane;
               
            }));
        }

        private void btnStopListen_Click(object sender, EventArgs e)
        {
            this.btnStopListen.Enabled = false;
            this.ListenButton.Enabled = true;
            xmlTcpServerEntity.StopListen();
            this.ConsoleTextBox.AppendText($"停止侦听.{ Environment.NewLine}");
        }

        private void SettingButton_Click(object sender, EventArgs e)
        {
            //当开始监听后，打开配置界面时，自动获取服务端的IP和端口号。
            SettingForm settingForm = new SettingForm();
            GetServerIpHandler delg;
            delg = new GetServerIpHandler(settingForm.ShowServerIp);            
            delg(this.ipTextBox.Text);
            delg = new GetServerIpHandler(settingForm.ShowServerIpPort);
            delg(this.tbxPort.Text);

            settingForm.Show();
        }


        private void dataGridViewFLow_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                MessageBox.Show("必须选择列头才能隐藏该列");
                return;
            }
            if (this.dataGridViewFLow.Columns[e.ColumnIndex].HeaderText == "LaneID")
            {
                MessageBox.Show("LaneID列不能被隐藏");
                return;
            }

            if (MessageBox.Show("确认隐藏该列？", "此操作恢复需要重新打开软件", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.dataGridViewFLow.Columns[e.ColumnIndex].Visible = false;
            }
        }
    }
}
